package com.yupi.springbootinit.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * MP注入处理器
 * @author 穹龙
 * @date 2025/2/11
 */
@Slf4j
public class InjectionMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject)) {
                // 检查createTime字段是否存在并且没有值
                if (metaObject.hasGetter("createTime") && metaObject.getValue("createTime") == null) {
                    metaObject.setValue("createTime", LocalDateTime.now());
                }
                // 检查updateTime字段是否存在并且没有值
                if (metaObject.hasGetter("updateTime") && metaObject.getValue("updateTime") == null) {
                    metaObject.setValue("updateTime", LocalDateTime.now());
                }
                // 检查isDelete字段是否存在并且没有值
                if (metaObject.hasGetter("isDelete") && metaObject.getValue("isDelete") == null) {
                    // 默认值为0，表示未删除
                    metaObject.setValue("isDelete", 0);
                }
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "自动注入异常 => " + e.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject)) {
                // 检查updateTime字段是否存在并且没有值
                if (metaObject.hasGetter("updateTime")) {
                    metaObject.setValue("updateTime", LocalDateTime.now());
                }
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "自动注入异常 => " + e.getMessage());
        }
    }
}
